package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.RecordAdapter;
import flc.ast.bean.AlbumBean;
import flc.ast.bean.RecordBean;
import flc.ast.databinding.ActivityAlbumBinding;
import flc.ast.utils.Content;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.utils.UriUtil;

public class AlbumActivity extends BaseAc<ActivityAlbumBinding> {

    public static String albumPath;
    private List<RecordBean> listShow = new ArrayList<>();
    private RecordAdapter recordAdapter;
    private int selPosition;
    private Dialog myEditDialog, myRenameDialog, myDeleteDialog;
    private EditText dialogRename;

    @Override
    protected int onCreate() {
        return R.layout.activity_album;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event5Container);
        String albumName = albumPath.substring(1);
        mDataBinding.tvAlumName.setText(albumName);
        mDataBinding.ivAlbumBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.tvImportVideo.setOnClickListener(this);
        mDataBinding.rvVideoList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        recordAdapter = new RecordAdapter();
        mDataBinding.rvVideoList.setAdapter(recordAdapter);
        recordAdapter.addChildClickViewIds(R.id.ivRecordItemEdit);
        recordAdapter.setOnItemChildClickListener(this);
        recordAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvImportVideo:
                gotoAlbum();
                break;
            case R.id.tvDialogEditRename://重命名
                renameDialog();
                myEditDialog.dismiss();
                myRenameDialog.show();
                dialogRename.setText(listShow.get(selPosition).getName());
                break;
            case R.id.tvDialogRenameConfirm:
                if (dialogRename.getText().toString().trim().isEmpty()) {
                    ToastUtils.showShort(getString(R.string.name_not_null));
                    return;
                }
                FileUtils.rename(listShow.get(selPosition).getPath(), dialogRename.getText().toString().trim() + ".mp4");
                getData();
                myRenameDialog.dismiss();
                break;
            case R.id.tvDialogRenameCancel:
                myRenameDialog.dismiss();
                break;
            case R.id.tvDialogEditShare://分享
                share(listShow.get(selPosition).getPath());
                break;
            case R.id.tvDialogEditDelete://删除
                deleteDialog();
                myEditDialog.dismiss();
                myDeleteDialog.show();
                break;
            case R.id.tvDialogDeleteVideoConfirm:
                FileUtils.delete(listShow.get(selPosition).getPath());
                getData();
                myDeleteDialog.dismiss();
                break;
            case R.id.tvDialogDeleteVideoCancel:
                myDeleteDialog.dismiss();
                break;
            case R.id.tvDialogEditCancel://取消
                myEditDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        PlayLocalActivity.videoPath = recordAdapter.getItem(position).getPath();
        startActivity(PlayLocalActivity.class);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivRecordItemEdit:
                editDialog();
                myEditDialog.show();
                selPosition = position;
                break;
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void share(String path) {
        Uri uri = UriUtil.path2Uri(mContext, path);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("video/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(intent, "Share"));
    }

    //获取相册数据
    private void getData() {
        listShow.clear();
        String path = PathUtils.getFilesPathExternalFirst() + albumPath;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                String time = TimeUtils.getNowString(new SimpleDateFormat("yyyy/MM/dd"));
                listShow.add(new RecordBean(FileUtils.getFileName(file.getPath()),
                        TimeUtil.getMmss(MediaUtil.getDuration(file.getPath())), FileUtils.getSize(file.getPath()),
                        time, file.getPath()));
            }
        }
        if (listShow.size() > 0) {
            recordAdapter.setList(listShow);
            mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
            mDataBinding.tvAlbumNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvVideoList.setVisibility(View.GONE);
            mDataBinding.tvAlbumNoData.setVisibility(View.VISIBLE);
        }
    }

    //去到系统选择导入视频界面
    private void gotoAlbum() {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT < 19) {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        } else {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        }
        intent.setType("video/*");
        startActivityForResult(intent, Content.REQUEST_VIDEO_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Content.REQUEST_VIDEO_CODE) {
            //获取视频路径
            Uri uri = data.getData();
            String resultFile = FileUtil.generateFilePath(albumPath, ".mp4");
            if (TextUtils.isEmpty(resultFile)) return;
            FileP2pUtil.copyToPrivate(uri, resultFile);
            getData();
            ToastUtils.showShort(R.string.import_suc);
        }
    }

    //编辑弹框
    private void editDialog() {
        myEditDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_edit, null);
        myEditDialog.setContentView(inflate);
        myEditDialog.setCancelable(true);
        Window dialogWindow = myEditDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView rename = inflate.findViewById(R.id.tvDialogEditRename);
        TextView share = inflate.findViewById(R.id.tvDialogEditShare);
        TextView delete = inflate.findViewById(R.id.tvDialogEditDelete);
        TextView cancel = inflate.findViewById(R.id.tvDialogEditCancel);
        rename.setOnClickListener(this);
        share.setOnClickListener(this);
        delete.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogRenameConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogRenameCancel);
        dialogRename = inflate.findViewById(R.id.etDialogRenameText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete_video, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(false);
        //获取当前Activity所在的窗体
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogDeleteVideoCancel);
        TextView right = inflate.findViewById(R.id.tvDialogDeleteVideoConfirm);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

}